<?php

class UserController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/mainUser';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}
    
    public function actions()
    {
        /**
    	 * Declares class-based actions.
    	 */
        return array(
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
		);
    }

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('register','captcha','recovery'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('index','info','edit','changePassword','changeAvatar'),
				'roles'=>array('Authenticated'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
    
    public function actionIndex()
    {        
        $loadList = new Loadlist('search');
		$loadList->unsetAttributes();  // clear any default values
        $loadList->user_id = Yii::app()->user->id;
        
        $vehicleList = new Vehiclelist('search');
        $vehicleList->unsetAttributes();  // clear any default values
        $vehicleList->user_id = Yii::app()->user->id;
        
        $this->render('index',array(
            'loadList'=>$loadList,
            'vehicleList'=>$vehicleList
        ));
    }

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionInfo()
	{
	   	$model = $this->loadModel(Yii::app()->user->id);
	   	
		$this->render('info',array(
			'model'=>$model,
            'profile'=>$model->profile
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionEdit()
	{
		$model = $this->loadModel(Yii::app()->user->id);        
        
        $profile = $model->profile;
        if($profile == null) {
            $profile = new Profile();
            $profile->user_id = $model->id;
            $profile->save();
        }
        
        $place = $model->default_place;
        if($place == null) {
            $place = new Place();
            $place->save();
            $model->saveAttributes(array('place_id'=>$place->id));
        }

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(Yii::app()->request->isPostRequest) {
            if(isset($_POST['Profile']))
    		{
    			$profile->attributes=$_POST['Profile'];
                
                if(!empty($_POST['birthday_year'])) {
                    $d = (int)$_POST['birthday_day'];
                    $m = (int)$_POST['birthday_month'];
                    $y = (int)$_POST['birthday_year'];
                    $profile->birthday = mktime(0,0,0,$m,$d,$y);
                }
                
                $profile->identify_card_picture = CUploadedFile::getInstance($profile,'identify_card_picture');
                if($profile->identify_card_picture !== null  && $profile->validate(array('identify_card_picture')))
                {
                    $imageFileName = '/images/identify_cards/'.$model->username.'.'.$profile->identify_card_picture->extensionName;
                    $profile->identify_card_picture->saveAs(Yii::app()->basePath.$imageFileName);
                    $profile->identify_card_picture = $imageFileName;
                }
            }
            
            if(isset($_POST['Place']))
                $place->attributes = $_POST['Place'];
                
            if($profile->save() && $place->save())
    			$this->redirect(array('info'));
        }

		$this->render('edit',array(
            'model'=>$model,
			'profile'=>$profile,
            'place'=>$place
		));
	}
    
    /**
     * Registration
     */
    public function actionRegister()
    {
        $this->layout = '//layouts/main';
        
        $model = new RegistrationForm;
        $profile = new Profile('register');
        
        $userComponent = Yii::app()->usercomponent;
        
	    if (!Yii::app()->user->isGuest) {
	    	$this->redirect(array("/site/index"));
	    } 
        else {
	    	if(isset($_POST['RegistrationForm'])) {
				$model->attributes=$_POST['RegistrationForm'];
				//$profile->attributes=((isset($_POST['Profile'])?$_POST['Profile']:array()));
				if($model->validate())
				{
					$sourcePassword = $model->password;
					$model->active_key = $userComponent->encrypting(microtime().$model->password);
					$model->password = $userComponent->encrypting($model->password);
					$model->verifyPassword = $userComponent->encrypting($model->verifyPassword);
					$model->lastvisit = (($userComponent->loginNotActiv||($userComponent->activeAfterRegister&&$userComponent->sendActivationMail==false))&&$userComponent->autoLogin)?time():0;
					$model->superuser = User::NOT_SUPERUSER;
					//$model->status = (($userComponent->activeAfterRegister) ? User::STATUS_ACTIVE : User::STATUS_NOACTIVE);
                    
                    if($model->save()) {
						$profile->user_id = $model->id;
						$profile->save();
                        
						if($userComponent->sendActivationMail) {
							$activation_url = $this->createAbsoluteUrl('/user/activation',array("active_key" => $model->active_key, "email" => $model->email));
							$userComponent->sendMail(
								$model->email,
								Yii::t("mail","{site_name} - Kích hoạt tài khoản",array('{site_name}'=>Yii::app()->name)),
								Yii::t("mail","Cảm ơn bạn đã đăng ký tại Datxe.vn. Vui lòng click vào đường dẫn bên dưới để kích hoạt tài khoản của bạn.")."<br/>".$activation_url
							);
						}
						
						if(($userComponent->loginNotActiv||($userComponent->activeAfterRegister&&$userComponent->sendActivationMail==false))&&$userComponent->autoLogin) {
                            //assign user-role    
                            Yii::app()->authManager->assign('Authenticated',$model->id);
                            $identity = new UserIdentity($model->username,$sourcePassword);
                            $identity->authenticate();
                            Yii::app()->user->login($identity,0);
                            $this->redirect(array("/site/index"));
						} else {
							if (!$userComponent->activeAfterRegister && !$userComponent->sendActivationMail) {
								Yii::app()->user->setFlash('registration',Yii::t("message","<strong>Cảm ơn bạn đã đăng ký.</strong> Vui lòng liên hệ Admin để kích hoạt tài khoản."));
							} elseif($userComponent->activeAfterRegister && $userComponent->sendActivationMail==false) {
								Yii::app()->user->setFlash('registration',Yii::t("message","<strong>Cảm ơn bạn đã đăng ký.</strong> Vui lòng đăng nhập để bắt đầu sử dụng."));
                                $this->redirect(Yii::app()->user->loginUrl);
							} elseif($userComponent->loginNotActiv) {
								Yii::app()->user->setFlash('registration',Yii::t("message","<strong>Cảm ơn bạn đã đăng ký.</strong> Vui lòng kiểm tra email hoặc đăng nhập."));
							} else {
								Yii::app()->user->setFlash('registration',Yii::t("message","<strong>Cảm ơn bạn đã đăng ký.</strong> Vui lòng kiểm tra email."));
							}
							$this->render('registration');
                            Yii::app()->end();
						}
					}
                }
			}
        }
        $this->render('registration',array(
            'model'=>$model,
        ));
    }
    
    /**
     * This is the action to recover password
     */
    public function actionRecovery()
    {
        $this->layout = '/layouts/main';
        
        $model = new RecoveryForm;
        
		if(!Yii::app()->user->isGuest)
            $this->redirect(Yii::app()->homeUrl);
        else {
			$email = ((isset($_GET['email']))?$_GET['email']:'');
			$activkey = ((isset($_GET['activkey']))?$_GET['activkey']:'');
			if($email&&$activkey) {
				$changePassForm = new ChangePasswordForm;
	    		$user = User::model()->notsafe()->findByAttributes(array('email'=>$email));
	    		if(isset($user)&&$user->activkey==$activkey) {
		    		if(isset($_POST['ChangePasswordForm'])) {
						$changePassForm->attributes = $_POST['ChangePasswordForm'];
						if($changePassForm->validate()) {
							$user->password = Yii::app()->usercomponent->encrypting($changePassForm->password);
							$user->activkey = Yii::app()->usercomponent->encrypting(microtime().$changePassForm->password);
							if($user->status == User::STATUS_NOACTIVE)
								$user->status = User::STATUS_ACTIVE;
							$user->save();
							Yii::app()->user->setFlash('changepass',Yii::t("message","New password is saved successfully."));
							$this->redirect(array("/site/index"));
						}
					} 
					$this->render('changepassword',array('model'=>$changePassForm));
	    		}
                else {
	    			Yii::app()->user->setFlash('recovery',Yii::t("message","Incorrect recovery link."));
					//$this->redirect(Yii::app()->controller->module->recoveryUrl);
	    		}
	    	}
            else {
		    	if(isset($_POST['RecoveryForm'])) {
		    		$model->attributes = $_POST['RecoveryForm'];
		    		if($model->validate()) {
		    			$user = $this->loadModel($model->user_id);
		    			
						$recovery_url = $this->createAbsoluteUrl('/site/recovery',array("activkey"=>$user->activkey, "email"=>$user->email));							
						$subject = Yii::t("mail","{site_name} - Recover your password",	array('{site_name}'=>Yii::app()->name));
						$message = Yii::t("mail","You or someone requested recover {username}'s password at Maximath. Please follow the link below to reset password.<br/> {url}",array(
                            "{username}"=>$user->username,
                            "{url}"=>$recovery_url
                        ));
                        
		    			Yii::app()->usercomponent->sendMail($user->email,$subject,$message);
		    			
						Yii::app()->user->setFlash('recovery',Yii::t("message","Please check your email. An instruction was sent to your email address."));
		    			$this->render('recovery');
                        Yii::app()->end();
		    		}
		    	}
	    	}
	    }
    		
        $this->render('recovery',array('model'=>$model));
    }
    
    public function actionChangePassword()
    {
        $user = $this->loadModel(Yii::app()->user->id);
        $model = new ChangePasswordForm;
		if(Yii::app()->user->isGuest) {
            throw new CHttpException(404,'The requested page does not exist.');
        }
        else {
			// ajax validator
			if(isset($_POST['ajax']) && $_POST['ajax']==='changepassword-form')
			{
				echo UActiveForm::validate($model);
				Yii::app()->end();
			}
			
			if(isset($_POST['ChangePasswordForm'])) {
				$model->attributes = $_POST['ChangePasswordForm'];
				if($model->validate()) {
					$user->password = Yii::app()->usercomponent->encrypting($model->password);
					$user->active_key = Yii::app()->usercomponent->encrypting(microtime().$model->password);
					$user->save();
					Yii::app()->user->setFlash('changepass',Yii::t("message","New password is saved successfully."));
					$this->redirect(Yii::app()->user->loginUrl);
				}
			}
			$this->render('changepassword',array('model'=>$model,'user'=>$user));
	    }
    }
    
    public function actionChangeAvatar()
    {        
        $model = $this->loadModel(Yii::app()->user->id);
        $profile = $model->profile;
        
        if(isset($_POST['Profile'])) {
            $profile->attributes = $_POST['Profile'];
            
            $imageUploadFile = CUploadedFile::getInstance($profile,'picture');
    		
            if($profile->validate()) {
    			if ($imageUploadFile instanceof CUploadedFile) {
    			    //$avatarPath = Yii::app()->basePath . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'avatars';
                    
                    $imageFileName = '/images/avatar/' . $model->username . '.' . $imageUploadFile->extensionName;
                    //$imageThumbName = '/images/avatar/'. $model->username . '_thumb.' . $imageUploadFile->extensionName;
                    
    				$profile->picture = $imageFileName;
                    
                    if($profile->save()) {
                        if($imageUploadFile->saveAs(Yii::app()->basePath . $imageFileName)) {
                            $image = Yii::app()->image->load(Yii::app()->basePath . $imageFileName);
                            $image->resize(80,80);
                            $image->save();
                            
                            //$image->resize(80,80);
                            //$image->save(Yii::app()->basePath . $imageThumbName);
        				    
                            Yii::app()->user->setFlash('success',Yii::t('message','The image was uploaded successfully'));
                        }
        				$this->redirect('info');
                    }
    			}
    		}
        }
        
        $this->render('changeavatar',array('profile'=>$profile)); 
    }

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=User::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
